package serial;

import java.io.IOException;

import mainWindow.MainWindow;
import net.tinyos.message.Message;
import net.tinyos.message.MessageListener;
import net.tinyos.message.MoteIF;
import net.tinyos.packet.PhoenixSource;

	//	This class handles sending packets to and from the serial port
	// 	The main window will invoke an instance of this class when it is instantiated
	//	This method used to connect and send the data is based on the TestSerial program located in the tutorial section included with tinyOS


public class SerialSender implements MessageListener{

	private MoteIF _moteIF;
	private String returnedString;
	private int returnedlength;
	private MainWindow _main;

		/*
		 * Constructor for serial sender class
		 * Create a new moteIF for serial device "phoenix" (Speficied when MainWindow is launched)
		 */
	public SerialSender( PhoenixSource phoenix, MainWindow main)
	{
		this._moteIF = new MoteIF(phoenix);
		this._moteIF.registerListener(new codeMsg(), this);
		_main = main;
	}

		/*
		 * This method sends data to the serial device
		 * The parameters are:
		 *  codeLine, the string to the be sent
		 *  segmentSize, the length of 1 segment
		 */
	public void sendToSerial(String codeLine, int segmentSize) throws InterruptedException
	{
		codeMsg payload = new codeMsg(segmentSize);			// Create new serial message, codeMsg, of size segmentSize 
		payload.setString_code(codeLine);					// Set the payload of the message to the string passed in


		try {
			_moteIF.send(0, payload);						// Send the packet

		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.err.println("fail at full line send");
			e.printStackTrace();
		}



	}


	@Override
	public void messageReceived(int to, Message message) {
		// TODO Auto-generated method stub
		System.out.println("I recieved this from the mote " + message.getSerialPacket().getString_data());
		returnedString = message.getSerialPacket().getString_data();
		returnedlength = returnedString.length();
		
		if(returnedlength!=0)
		{	
		int i;
		int tempInt;
		int data[] = new int[returnedlength];
		
		for(i=0;i<returnedlength;i++)
		{
			tempInt= Integer.parseInt(returnedString.substring(i, i+1));
			data[i] = tempInt;
			_main.consoleText.append("m"+i+" = " + data[i] +"\n");
			System.out.println(data[i]);
		}
		}

	}
	
//	public int[] getFeedbackInt()
//	{
//		int i;
//		int tempInt;
//		
//		for(i=0;i<returnedlength;i++)
//		{
//			tempInt= Integer.parseInt(returnedString.substring(i, i+1));
//			data[i] = tempInt;
//			System.out.println(data[i]);
//		}
//		
//		return data;
//	}


}
